angular.module('myApp', ['infinite-scroll']);
showLoading();

function huati($scope, $http) {
	var topicId;
	var phone = readData(localStorage.phone);
	var clicentId = phone.substring(0, 3) + '****' + phone.substring(7);
	url = getUrl("41circleTopic");
	header = getHeader();
	$scope.pages = 0;
	//默认加载第一页，初始值0
	$scope.topics = [];
	$scope.totalpage = 1;
	//总页数初始默认1，读取数据后再更新
	$scope.loadMore = function() {
			if ($scope.pages < $scope.totalpage) {
				params = 'userId=' + readData(localStorage.guideId) + '&indexpage=' + $scope.pages + '&accountId=' + readData(localStorage.account) + '&pageSize=5';
				$scope.pages = $scope.pages + 1;
				$http({
					method: 'POST',
					url: url,
					headers: header,
					timeout: 10000,
					//cache: true,
					data: params
				}).success(function(data, status, headers, config) {
					if (data.obj) {
						var topics = data.obj.topicList;
						for (var i = 0; i < topics.length; i++) {
							var pic = topics[i]['images']
							topics[i]['createTime'] = topics[i]['createTime'].split('.')[0];
							var pics = [];
							if (topics[i]['images']) {
								while (pic.length > 0 && pic != 'null') {
									if (pic.indexOf(',') == -1) {
										pics.push({
											pic: pic
										});
										pic = '';
									} else {
										pic1 = pic.substring(0, pic.indexOf(','))
										pic = pic.substring(pic.indexOf(',') + 1)
										pics.push({
											pic: pic1
										})
									}
								}
							}
							if (!topics[i].pic) {
								topics[i].pic = "../../image/small.png";
							}
							if (topics[i].replyList) {
								for (var g in topics[i].replyList) {
									if (!topics[i].replyList[g].nickname) {
										topics[i].replyList[g].nickname = "导购";
									}
								}
							}
							//根据赞的状态zanStatus判断 等待接口改动
							if (topics[i]["zanStatus"] == "1") {
								topics[i]["zanstatustext"] = "取消"
							} else {
								topics[i]["zanstatustext"] = "赞"
							}
							//判断赞列表是否有值
							if (topics[i]["zanList"]) {
								topics[i]["zanListstatus"] = true;
								topics[i]["people"] = topics[i]["zanList"].length;
								for (var j = 0; j < topics[i]["zanList"].length; j++) {
									if (!topics[i]["zanList"][j]) {
										topics[i]["zanList"][j] = "导购";
									}
								}
							} else {
								topics[i]["zanListstatus"] = false;
								topics[i]["people"] = 0;
							}
							topics[i]['images'] = pics;
							$scope.topics.push(topics[i]);
						}
						$scope.totalpage = data.obj.totalpage;

						//下拉页面+1
					} else {
						$scope.topics = [];
						$scope.pages = $scope.pages - 1;
						if (data.code == "3") {

							document.getElementById("nohuati").style.display = "block";
						}
					}
					removeLoading()
				}).error(function(data, status, headers, config) {
					console.log("topic load is erro")
					$scope.pages = $scope.pages - 1;
				});
			}
		}
		//点赞
	$scope.zan = function(tId) {
			urlZan = getUrl("42zanTopic");
			headerZan = getHeader();
			paramsZan = 'id=' + tId + '&userId=' + readData(localStorage.account);
			plus.nativeUI.showWaiting("请等待……");
			$http({
				method: 'POST',
				url: urlZan,
				headers: headerZan,
				timeout: 10000,
				//cache: true,
				data: paramsZan
			}).success(function(data, status, headers, config) {
				plus.nativeUI.closeWaiting();
				if (data.code == '0') {
					for (var i in $scope.topics) {
						// 重复点赞功能待处理
						if ($scope.topics[i]['id'] == tId) {
							if (data.obj.zanList) {
								for (var j = 0; j < data.obj.zanList.length; j++) {
									if (!data.obj.zanList[j]) {
										data.obj.zanList[j] = "导购";
									}
								}
								$scope.topics[i]['zanList'] = data.obj.zanList;
								$scope.topics[i]["people"] = data.obj.zanList.length;
								$scope.topics[i]["zanListstatus"] = true;
								if (data.obj.zanStatus == "1") {
									$scope.topics[i]['zanStatus'] = 1;
									$scope.topics[i]["zanstatustext"] = "取消";
								} else {
									$scope.topics[i]['zanStatus'] = 0;
									$scope.topics[i]["zanstatustext"] = "赞";
								}
							} else {
								$scope.topics[i]["zanListstatus"] = false;
								$scope.topics[i]["zanstatustext"] = "赞";
							}
						}
					}
				} else {
					mui.toast('网络连接异常，请稍后重试' + data.code);
				};
			}).error(function() {
				console.log("topic zan is erro");
			});
		}
		//评论标志
	$scope.pl = function(tId) {
			topicId = tId;
		}
		//评论提交
	$scope.reply = function() {
		urlReply = getUrl("43replyTopic");
		headerReply = getHeader();
		paramsReply = 'topicId=' + topicId + '&userId=' + readData(localStorage.account) + '&content=' + utf16toEntities(document.getElementById('pl').value);
		alert(paramsReply)
		plus.nativeUI.showWaiting("请等待……");
		$http({
			method: 'POST',
			url: urlReply,
			headers: headerReply,
			timeout: 10000,
			//cache: true,
			data: paramsReply
		}).success(function(data, status, headers, config) {
			if (data.code == '0') {
				for (var i = 0; i < $scope.topics.length; i++) {
					if ($scope.topics[i]['id'] == topicId) {
						if ($scope.topics[i]['replyList']) {
							$scope.topics[i]['replyList'].push({
								nickname: readData(localStorage.nickName),
								content: document.getElementById('pl').value
							})
						} else {
							$scope.topics[i]['replyList'] = [{
								nickname: readData(localStorage.nickName),
								content: document.getElementById('pl').value
							}];
						}
					}
				}
				document.getElementById('pl').value = '';
				check(document.getElementById('pl'));
				hide();
			} else {
				mui.toast('网络连接异常，请稍后重试' + data.code);
			};
			plus.nativeUI.closeWaiting();
		}).error(function() {
			console.log("topic zan is erro");
		});
	}
}
var btn = document.getElementById("btn");
var sendbox = document.getElementById("send");

function check(obj) { //改变发送按钮状态
	var str = obj.value.replace(/\s/g, "");
	if (str.length > 0) {
		btn.className = "btnactive";
		btn.removeAttribute("disabled");
	} else {
		btn.className = "ibtn";
		btn.setAttribute("disabled", true);
	}
} //编辑框隐藏与现实

function show(event) {
	sendbox.style.display = "block";
	document.getElementById("pl").focus();
	event.stopPropagation();
	event.cancelBubble = true;
}

function hide() {
	sendbox.style.display = "none";
}
/*
 把表情转义为字符实体
 @params {string} str为评论内容
 @return str{string}
 * */
function utf16toEntities(str) {
	var patt = /[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则
	str = str.replace(patt, function(char) {
		//alert(char);
		var H, L, code;
		if (char.length === 2) {
			H = char.charCodeAt(0); // 取出高位
			L = char.charCodeAt(1); // 取出低位
			code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法
			return "&#" + code + ";";
		} else {
			return char;
		}
	});
	return str;
}
/*		 
 * 初始化图片 使得图片大小统一
 * listimg为页面中的图片对象
 */
var max = document.documentElement.clientWidth;

function initImg(listimg) {
	listimg.parentNode.style.height = (max - 80) / 3.0 + "px";
}